package com.brspace.qualitycontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.brspace.qualitycontrol.entity.*;
import com.brspace.qualitycontrol.mapper.*;
import com.brspace.qualitycontrol.service.PeopleHotlineService;
import com.brspace.qualitycontrol.utils.EmptyUtil;
import com.brspace.qualitycontrol.utils.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 百姓热线 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-05-06
 */
@Service
public class PeopleHotlineServiceImpl extends ServiceImpl<PeopleHotlineMapper, PeopleHotline> implements PeopleHotlineService {
    @Resource
    private ProcessMapper processMapper;
    @Resource
    private ProcessNodeMapper nodeMapper;
    @Resource
    private ProcessRouterMapper routerMapper;
    @Resource
    private HandleMapper handleMapper;
    /**
     * 审核
     * @Author wangt
     * @Date 2021-05-06 14:40:20
     */
    @Override
    public R examine(PeopleHotline peopleHotline,String xiaUser, String dangUser) {
        if (peopleHotline.getNodeId()==0) {
            throw new SecurityException("流程已结束！");
        }
        if ("退回".equals(peopleHotline.getProgress())){
            if ("undefined".equals(xiaUser) || xiaUser==null || "null".equals(xiaUser)){
                Handle handleList = handleMapper.selectOne(new QueryWrapper<Handle>().eq("middleman_id", dangUser).eq("document_id", peopleHotline.getId()).eq("n_id",peopleHotline.getNodeId()));
                xiaUser=handleList.getHandleId();
            }
        }
        // 根据当前节点获取当前流程下的PID以及节点NodeName
        ProcessNode processNode = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("id", peopleHotline.getNodeId()));
        // 获取初始节点的ID
        int findId = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processNode.getPId()).eq("sort_num", 1)).getId();
        // 获取最后节点的ID
        int id = nodeMapper.selectOne(new QueryWrapper<ProcessNode>().eq("p_id", processNode.getPId()).orderByDesc("sort_num").last("limit 1")).getId();
        if (peopleHotline.getNodeId()==findId) {
            // 获取目标节点
            handleAdd(peopleHotline, peopleHotline.getUserId(), null, processNode.getPId());
            int i = routerMapper.selectOne(new QueryWrapper<ProcessRouter>().eq("current_id", peopleHotline.getNodeId()).eq("requirement",peopleHotline.getProgress())).getTargetId();
            peopleHotline.setNodeId(i);
            handleAdd(peopleHotline, xiaUser, peopleHotline.getUserId(), processNode.getPId());
            baseMapper.updateById(peopleHotline);
            return R.ok();
        }
        // 获取当前节点的信息
        List<ProcessRouter> processRouters = routerMapper.selectList(new QueryWrapper<ProcessRouter>().eq("current_id", peopleHotline.getNodeId()).eq("requirement", peopleHotline.getProgress()));
        if ("同意".equals(peopleHotline.getProgress())){
            examineIf(peopleHotline,processRouters,id,dangUser,xiaUser,processNode.getPId());
            return R.ok();
        }
        if ("转接收".equals(peopleHotline.getProgress())){
            xiaUser=peopleHotline.getUserId();
            examineIf(peopleHotline,processRouters,id,dangUser,xiaUser,processNode.getPId());
            return R.ok();
        }
        if ("退回".equals(peopleHotline.getProgress())){
            for (ProcessRouter router : processRouters) {
                System.out.println("驳回");
                peopleHotline.setNodeId(router.getTargetId());
                Handle handle = new Handle();
                handle.setDocumentId(peopleHotline.getId())
                        .setHandleId(xiaUser)
                        .setMiddlemanId(dangUser)
                        .setPId(processNode.getPId());
                handleMapper.insert(handle);
                baseMapper.updateById(peopleHotline);
                return R.ok();
            }
        }

        return R.error().data("message","问就是出现异常！");
    }

    private void examineIf(PeopleHotline peopleHotline, List<ProcessRouter> processRouters, int id, String dangUser, String xiaUser, int pId) {
        for (ProcessRouter router : processRouters) {
            if (router.getTargetId()==id){
                System.err.println("目标节点等于最后节点");
                peopleHotline.setNodeId(0);
                Handle handle = new Handle();
                handle.setDocumentId(peopleHotline.getId())
                        .setHandleId(dangUser)
                        .setNId(router.getTargetId())
                        .setPId(router.getPId());
                handleMapper.insert(handle);
                baseMapper.updateById(peopleHotline);
            }else {
                if ("undefined".equals(xiaUser) || xiaUser==null || "null".equals(xiaUser)){
                    throw new SecurityException("请选择下阶段办理人！");
                }
                System.err.println("进入下一个节点");
                peopleHotline.setNodeId(router.getTargetId());
                handleAdd(peopleHotline,xiaUser,dangUser, pId);
                baseMapper.updateById(peopleHotline);
            }
        }
    }

    @Override
    public IPage<PeopleHotline> selectPage(Page<PeopleHotline> pageParam, Object o) {
        return baseMapper.selectPage(pageParam,null);
    }

    /**
     * 添加
     * @Author wangt
     * @Date 2021-05-06 14:06:48
     */
    @Override
    public int add(PeopleHotline peopleHotline) {
        // 校验
        this.check(peopleHotline);
        int i = baseMapper.insert(peopleHotline);
        if (i>0) {
            peopleHotline.setProgress("同意");
            examine(peopleHotline,peopleHotline.getFenId(),peopleHotline.getUserId());
        }
        return i;
    }
    /**
     * 根据ID查一个
     * @Author wangt
     * @Date 2021-05-06 14:35:59
     */
    @Override
    public Object findById(String id) {
        return baseMapper.selectById(id);
    }


    private void check(PeopleHotline peopleHotline) {
        if (peopleHotline.getLetterTime().getTime() >= peopleHotline.getReplyTime().getTime()) {
            throw new SecurityException("答复日期不能小于信访日期！");
        }
        if (EmptyUtil.isEmpty(peopleHotline.getUserId())) {
            throw new SecurityException("当前创建人为空！");
        }
        if (EmptyUtil.isEmpty(peopleHotline.getFenId())){
            throw new SecurityException("请选择分管领导！");
        }
    }

    private void handleAdd(PeopleHotline letter, String daiId, String xianId, int id) {
//        handleMapper.delete(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("middleman_id", daiId));
//        handleMapper.delete(new QueryWrapper<Handle>().eq("document_id", letter.getId()).eq("handle_id", daiId));
        Handle handle = new Handle();
        if (daiId==null){
            handle.setMiddlemanId(letter.getUserId());
        }else {
            handle.setMiddlemanId(daiId);
        }
        handle.setDocumentId(letter.getId())
                .setHandleId(xianId)
                .setPId(id).setNId(letter.getNodeId());
        handleMapper.insert(handle);
    }
}
